package cn.uncode.springcloud.utils.sensitive.pattern;

import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpressionConverter extends BaseConverter {

    @Override
    public String invokeMsg(String oriMsg) {
        String tempMsg = oriMsg;
        Pattern pattern;
        try {
            if ("true".equals(converterCanRun)) {
                if (!keywordMap.isEmpty()) {
                    Set<String> keysArray = keywordMap.keySet();
                    for (String key : keysArray) {
                        pattern = Pattern.compile(key);
                        Matcher matcher = pattern.matcher(tempMsg);
                        int i = 0;
                        while (matcher.find() && (i < depth)) {
                            i++;
                            int valueStart = matcher.start();
                            int valueEnd = matcher.end();
                            if (valueStart < 0 || valueEnd < 0) {
                                break;
                            }
                            String subStr = matcher.group();
                            subStr = facade(subStr, keywordMap.get(key));
                            tempMsg = tempMsg.substring(0,valueStart) + subStr + tempMsg.substring(valueEnd);
                        }
                    }
                }
            }
        }catch (Exception e) {
            return tempMsg;
        }
        return tempMsg;
    }
}
